﻿using DevExpress.ExpressApp.Blazor.Components.Models;
using DevExpress.ExpressApp.Blazor.Editors;
using DevExpress.ExpressApp.DC;
using DevExpress.ExpressApp.Model;
using System.ComponentModel;

namespace EasyXaf.DynamicForm.Blazor;

public class DynamicFormEditor : BlazorPropertyEditorBase
{
    private IMemberInfo _schemaPropertyInfo;

    public DynamicFormEditor(Type objectType, IModelMemberViewItem model)
        : base(objectType, model)
    {
    }

    protected override IComponentModel CreateComponentModel()
    {
        var schema = string.Empty;
        var attribute = MemberInfo.FindAttribute<DynamicFormSchemaPropertyAttribute>();

        if (attribute != null)
        {
            _schemaPropertyInfo = MemberInfo.Owner.FindMember(attribute.PropertyName);
            if (_schemaPropertyInfo != null)
            {
                schema = _schemaPropertyInfo.GetValue(CurrentObject) as string;
                if (CurrentObject is INotifyPropertyChanged currentObject)
                {
                    currentObject.PropertyChanged += CurrentObject_PropertyChanged;
                }
            }
        }

        return new DynamicFormEditorModel
        {
            Schema = schema,
        };
    }

    protected override void Dispose(bool disposing)
    {
        if (CurrentObject is INotifyPropertyChanged currentObject)
        {
            currentObject.PropertyChanged -= CurrentObject_PropertyChanged;
        }

        base.Dispose(disposing);
    }

    private void CurrentObject_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (ComponentModel is DynamicFormEditorModel model && _schemaPropertyInfo != null)
        {
            model.Schema = _schemaPropertyInfo.GetValue(CurrentObject) as string;
        }
    }
}
